package com.topisv.tms.service.interfacetask;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.ExpressConfigure;
import com.topisv.tms.entity.WarehouseAddress;
import com.topisv.tms.entity.interfacetask.InterfaceTask;
import com.topisv.tms.entity.interfacetask.InterfaceTaskEnum;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.repository.EdiOrderDao;
import com.topisv.tms.repository.ExpressConfigureDao;
import com.topisv.tms.repository.work.WorkOrderDao;
import com.topisv.tms.rest.qimen.qmsend.QmRequestSender;
import com.topisv.tms.rest.qimen.qmservice.DeliveryOrderConfirmService;
import com.topisv.tms.rest.qimen.qmservice.DeliveryProcessService;
import com.topisv.tms.service.WarehouseAddressService;
import com.topisv.tms.task.interfacetask.SelfException;
import com.topisv.tms.utils.bsht.MailBSHTUtil;

/**
 * 接口任务处理
 * @author <a href="mailto:yuanlianghe@nryuncang.com">yuanlianghe</a>
 */
@Component
public class InterfaceTaskProcessService {
    private static final Logger logger = LoggerFactory.getLogger(InterfaceTaskProcessService.class);
    
    @Autowired
    private EdiOrderDao ediOrderDao;
    @Autowired
    private WorkOrderDao workOrderDao;
    @Autowired
    private ExpressConfigureDao expressConfigureDao;
    @Autowired
    private WarehouseAddressService warehouseAddressService;
    @Resource(type=DeliveryProcessService.class)
    private QmRequestSender<Map<String,Object>> deliveryProcessService;
    @Resource(type=DeliveryOrderConfirmService.class)
    private QmRequestSender<String> deliveryOrderConfirmService;
    
    
    public void process(InterfaceTask task) {
        String type = task.getType();
        
        if (InterfaceTaskEnum.TYPE_MAIL_BS.equals(type)) {
            mailBS(task);
            
        } else if (InterfaceTaskEnum.TYPE_QM_DELIVERY_PACKAGE.equals(type)) {
            deliveryPkg(task);
            
        } else if (InterfaceTaskEnum.TYPE_QM_DELIVERY_PROCESS.equals(type)) {
            deliveryProcess(task);
            
        } else if (InterfaceTaskEnum.TYPE_QM_DELIVERY_ORDER_CONFIRM.equals(type)) {
            deliveryOrderConfirm(task);
            
        } else if (InterfaceTaskEnum.TYPE_QM_DELIVERY_PICK.equals(type)) {
        	// add 20160621
        	deliveryPick(task);
        } else if (InterfaceTaskEnum.TYPE_QM_DELIVERY_CREATEBATCH.equals(type)) {
            // add 20161023
            deliveryCreateBatch(task);
        } else {
            throw new SelfException("未知的接口类型!");
        }
    }
    
    
    
    /**
     * 汇通发货反馈
     * @param task
     */
    public void mailBS(InterfaceTask task) {
        try {
            EdiOrder order = ediOrderDao.findByOrdeno(task.getRelatedNo());
            WorkOrder workOrder = workOrderDao.findOne(task.getRelatedId());
            
            ExpressConfigure ec = expressConfigureDao.findByWarehouseAndCompany(order.getWarehouseCode(), "HTKY");
            WarehouseAddress wha = warehouseAddressService.findByWarehouseCode(order.getWarehouseCode());
            
            try {
                MailBSHTUtil.deliveryRequestBack(order, ec, wha, workOrder.getEbillNo());
            } catch (Exception ex) {
                logger.error("处理汇通发货反馈接口遇到异常(请求处理过程).", ex);
                
                if (ex instanceof SelfException) {
                    throw ex;
                }
                throw new SelfException("处理汇通发货反馈接口遇到异常(请求处理过程).", ex);
            }
        } catch (Exception e) {
            if (e instanceof SelfException) {
                throw (SelfException) e;
            }
            
            logger.error("处理汇通发货反馈接口遇到异常(获取数据过程)", e);
            throw new SelfException("处理汇通发货反馈接口遇到异常(获取数据过程)", e);
        }
    }

    /**
     * [status:package]发送奇门出库单流水信息
     * @param task
     */
    public void deliveryPkg(InterfaceTask task) {
        EdiOrder ediOrder = ediOrderDao.findByOrdeno(task.getRelatedNo());
        
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("ediOrder", ediOrder);
        params.put("status", "package");
        
        String result = "";
        try {
            result = deliveryProcessService.send(params,ediOrder.getCustomerCode());
        } catch (Exception e) {
            logger.error("发送奇门出库单流水信息遇到异常(请求处理过程).", e);
            throw new SelfException("发送奇门出库单流水信息遇到异常(请求处理过程).", e);
        }
        
        if (!"success".equals(result)) {
            throw new SelfException("发送奇门出库单流水信息返回失败.");
        }
    }

    /**
     * [status:send]发送奇门出库单流水信息
     * @param task
     */
    public void deliveryProcess(InterfaceTask task) {
        EdiOrder ediOrder = ediOrderDao.findOne(task.getRelatedId());
        
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("ediOrder", ediOrder);
        params.put("status", "send");
        
        String result = "";
        try {
            result = deliveryProcessService.send(params,ediOrder.getCustomerCode());
        } catch (Exception e) {
            logger.error("发送奇门出库单流水信息遇到异常(请求处理过程).", e);
            throw new SelfException("发送奇门出库单流水信息遇到异常(请求处理过程).", e);
        }
        
        if (!"success".equals(result)) {
            throw new SelfException("发送奇门出库单流水信息返回失败.");
        }
    }

    /**
     * [status:pick]发送奇门出库单拣货
     * @param task
     */
    public void deliveryPick(InterfaceTask task) {
    	EdiOrder ediOrder = ediOrderDao.findOne(task.getRelatedId());
    	
    	Map<String,Object> params = new HashMap<String,Object>();
    	params.put("ediOrder", ediOrder);
    	params.put("status", "pick");
    	
    	String result = "";
    	try {
    		result = deliveryProcessService.send(params,ediOrder.getCustomerCode());
    	} catch (Exception e) {
    		logger.error("发送奇门出库单拣货遇到异常(请求处理过程).", e);
    		throw new SelfException("发送奇门出库单拣货遇到异常(请求处理过程).", e);
    	}
    	
    	if (!"success".equals(result)) {
    		throw new SelfException("发送奇门出库单拣货返回失败.");
    	}
    }
    
    /**
     * [status:CreateBatch]发送奇门出库单创建订单
     * @param task
     */
    public void deliveryCreateBatch(InterfaceTask task) {
        EdiOrder ediOrder = ediOrderDao.findOne(task.getRelatedId());
        
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("ediOrder", ediOrder);
        params.put("status", "createBatch");
        
        String result = "";
        try {
            result = deliveryProcessService.send(params,ediOrder.getCustomerCode());
        } catch (Exception e) {
            logger.error("发送奇门出库单创建订单遇到异常(请求处理过程).", e);
            throw new SelfException("发送奇门出库单创建订单遇到异常(请求处理过程).", e);
        }
        
        if (!"success".equals(result)) {
            throw new SelfException("发送奇门出库单创建订单返回失败.");
        }
    }

    /**
     * 发送奇门出库单确认信息
     * @param task
     */
    public void deliveryOrderConfirm(InterfaceTask task) {
        EdiOrder ediOrder = ediOrderDao.findOne(task.getRelatedId());
        
        String result = "";
        try {
            result = deliveryOrderConfirmService.send(task.getRelatedNo(), ediOrder.getCustomerCode());
        } catch (Exception e) {
            logger.error("发送奇门出库单确认信息遇到异常(请求处理过程).", e);
            throw new SelfException("发送奇门出库单确认信息遇到异常(请求处理过程).", e);
        }
        
        if (!"success".equals(result)) {
            throw new SelfException("发送奇门出库单流水信息返回失败.");
        }
    }
    
}
